﻿import os
import sys
import stat
import functools
import pygame
from pygame import surfarray
import rightnow6.pygameWindowInfo as pygameWindowInfo
from rightnow6.locals import *
from rightnow6.base import *


#pygame.init()
'''
default_settings = {
	"resizeable": False,
	"hasborder": True,
	"fullscreen": False,
	"screen_top": None,
	"screen_left": None,
	"screen_width": 640,
	"screen_height": 480,
}
'''

globlo_clock = pygame.time.Clock()
def Tick(fps):
	globlo_clock.tick(fps)
	
def GetWaitTime():
	return globlo_clock.get_time()

def ClearEvent():
	for event in pygame.event.get():
		pass

def GetKmState():
	km_state = {}
	km_state["key-state"] = pygame.key.get_pressed()
	p = pygame.mouse.get_pos()
	
	km_state["mouse-pos"] = Point(p[0], p[1])
	
	mp = pygame.mouse.get_pressed()	
	if mp[2] == 1:
		km_state["mousedown-right"] = True
	else:
		km_state["mousedown-right"] = False
		
	if mp[0] == 1:
		km_state["mousedown-left"] = True
	else:
		km_state["mousedown-left"] = False
	return km_state
	
def SaveSurface(surface, filename):
	pygame.image.save(surface, filename)


	
class PygameGraphSys():
	def __init__(self, **kwargs):
		self.isopend = False
		self.set_optinos(**kwargs)
		self.states = {}
		
		self.mouseon = True
		self.focus = True
		
	def set_optinos(self, **kwargs):
		if "resizeable" in kwargs and kwargs["resizeable"] == True:
			self.resizeable = True
		else:
			self.resizeable = False
		
		if "hasborder" in kwargs and kwargs["hasborder"] == False:
			self.hasborder = False
		else:
			self.hasborder = True
			
		if "autoclearbg" in kwargs and kwargs["autoclearbg"] == False:
			self.autoclearbg = False
		else:
			self.autoclearbg = True
			
		self.icon = None
		self.caption = None
		if "pos" in kwargs:
			screenx, screeny = kwargs["pos"][0], kwargs["pos"][1]
		else:
			screenx, screeny = 128, 128
		if "size" in kwargs:
			screenwidth, screenheight = kwargs["size"][0], kwargs["size"][1]
		else:
			screenwidth, screenheight = 800, 600
		#screenx, screeny, screenwidth, screenheight = 128, 128, 1024, 768
		self.size = self.width, self.height = screenwidth, screenheight
		os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (screenx, screeny)
		
		
	def open(self):
		if self.isopend:
			return
			
		pygame.display.init()
		flag = 0
		if self.resizeable:
			flag |= pygame.RESIZABLE
		if not self.hasborder:
			flag |= pygame.NOFRAME
	
		self.screen = pygame.display.set_mode(self.size, flag)
		self.winInfo = pygameWindowInfo.PygameWindowInfo()
		self.isopend = True
		
	def reopen(self, **kwargs):
		self.close()
		self.set_optinos(**kwargs)
		self.open()
		
	def close(self):
		if not self.isopend or not pygame.display.get_init():
			return
		pygame.display.quit()
		self.isopend = False
		
		
	def flip(self):
		if not self.isopend or not pygame.display.get_init():
			return True
			
		for event in pygame.event.get((pygame.QUIT, pygame.VIDEORESIZE,
										pygame.ACTIVEEVENT,)): #pygame.VIDEOEXPOSE)):
			if event.type == pygame.QUIT:
				self.close()
				return True
			if event.type == pygame.VIDEORESIZE and self.resizeable:
				WIDTH, HEIGHT = event.size
				self.screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
				self.width, self.height = (WIDTH, HEIGHT)
			
			# 已經包含在ACTIVEEVENT之中
			#if event.type == pygame.VIDEOEXPOSE:
			#	print("VIDEOEXPOSE")
			if event.type ==  pygame.ACTIVEEVENT:
				if event.state == 1:
					if event.gain == 1:
						self.mouseon = True
					else:
						self.mouseon = False
				
				if event.state == 2 and event.gain == 0:
					self.focus = False
				if event.state == 6 and event.gain == 1:
					self.focus = True
				
		self.winInfo.update()
			
		winPos = self.winInfo.getWindowPosition()
		screenPos = self.winInfo.getScreenPosition()
				
		pygame.display.flip()
		
		if self.autoclearbg:
			self.screen.fill((0,0,0))
		#pygame.display.update(rectangle=None)
		return False
		
	def _surface(self):
		if not self.isopend or not pygame.display.get_init():
			return None
		return self.screen
	


class PygameSoundSys():
	def __init__(self):
		pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
		pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
		self.queue = []
		self.nowframe = 0
		
	def addsound(self, sound, channel_limit=0, channel_limit_max=7):
		if len(self.queue) > 30:
			self.queue.pop(0)
		self.queue.append((sound, channel_limit, self.nowframe))
		

	def playback(self, nowframe):
		self.nowframe = nowframe
		remove_list = []
		for j in range(len(self.queue)):
			sound, channel_limit, frame = self.queue[j]
			if nowframe - frame > 30:
				remove_list.append(j)

		for poped in remove_list:
			self.queue.pop(poped)
			
		
		for i in range(pygame.mixer.get_num_channels()):
			chn = pygame.mixer.Channel(i)
			if not chn.get_busy():
				for j in range(len(self.queue)):
					sound, channel_limit, frame = self.queue[j]
					if channel_limit <= i:
						chn.queue(sound)
						self.queue.pop(j)
						break
				
	
# 之後才會繼續開發 目前暫時使用pygame	
"""
class PygameImage():
	def __init__(self):
		self._raw_surface = None
		self.hpoint = Point()
		self.width
		self.height
		self.boundingbox = Rect()
		
	def SetHangPoint(self, hpoint):
		if isinstance(hpoint, int) and hpoint == HPOINT_TOPLEFT:
			self.hpoint = Point(0, 0)
		elif isinstance(hpoint, int) and hpoint == HPOINT_TOPLEFT:
			self.hpoint = Point(self.width // 2, self.height // 2)
		else:
			self.hpoint = hpoint

class PygameSound():
	def __init__(self):
		self._raw_sound = None
		self.length = 0
"""
		
class PygameAlbum():
	"""
	>>> album = PygameAlbum()
	>>> str(album.fetch("test128x128_32_1"))
	"<Surface(128x128x32 SW)>"
	>>> "<Sound object at" in str(album.fetch("close_door_2"))
	True
	"""
	def __init__(self):
		self.library = {}
		self.path = ""
		
	def fetch(self, key):
		if key in self.library:
			return self.library[key][1]
		else:
		
			try:
				'''
				rawsurface = pygame.image.load(os.path.join(self.path, key + ".bmp"))
				image = PygameImage()
				image._raw_surface = rawsurface
				self.library[key] = image
				'''
				path = os.path.join(self.path, key + ".bmp")
				surface = pygame.image.load(path)
				lastmtime = os.stat(path).st_mtime
				self.library[key] = (path, surface, lastmtime)
				return self.library[key][1]
			except pygame.error:
				pass
				
			try:
				path = os.path.join(self.path, key + ".jpg")
				surface = pygame.image.load(path)
				lastmtime = os.stat(path).st_mtime
				self.library[key] = (path, surface, lastmtime)
				return self.library[key][1]
			except pygame.error:
				pass
				
			try:
				path = os.path.join(self.path, key + ".wav")
				#rawsound = pygame.mixer.Sound(path)
				#sound = PygameSound()
				#sound._raw_surface = rawsound
				sound = pygame.mixer.Sound(path)
				lastmtime = os.stat(path)
				self.library[key] = (path, sound, lastmtime)
				return self.library[key][1]
			except pygame.error:
				pass
				
			return None
			
	# 暫時不使用 這是用在資源修改後 自動重新載入資源
	def autoreload(self):
		reloadkeys = []
		for key in self.library.keys():
			path = self.library[key][0]
			if os.stat(path).st_mtime != self.library[key][2]:
				reloadkeys.append(key)
			
		# reload
		for key in reloadkeys:
			del self.library[key]
			self.fetch(key)
			

BLEND_NAME = {
	BLEND_COPY:0,
	BLEND_ADD:pygame.BLEND_ADD,
	BLEND_SUB:pygame.BLEND_SUB,
	BLEND_MUL:pygame.BLEND_MULT,
	BLEND_MIN:pygame.BLEND_MIN,
	BLEND_MAX:pygame.BLEND_MAX
}

CHANNEL_NAME = {
	CHANNEL_R:0,
	CHANNEL_G:1,
	CHANNEL_B:2,
	CHANNEL_A:3,
	CHANNEL_L:0,
	CHANNEL_1:0
}

#-----GraphEngine-----
class PygameGraphOperator():
	@staticmethod
	def _format2depth_(format):
		depth = 0
		if format == "RGB":
			depth = 24
		if format == "RGBA":
			depth = 32
		if format == "L":
			depth = 8
		return depth
	
	#---基本系列---
	@staticmethod
	def create(size, format):
		if format != "RGBA":
			return pygame.Surface((size[0], size[1]), 0, PygameGraphOperator._format2depth_(format))
		else:
			return pygame.Surface((size[0], size[1]), pygame.SRCALPHA, 32)
	@staticmethod
	def copy(surface):
		return surface.copy()
		
	#def fill(surface, color):
	#	return 
		
	@staticmethod
	def convert(surface, format):
		return surface.convert(PygameGraphOperator._format2depth_(format))
		
	@staticmethod
	def issame(surface1, surface2):
		if not (suf1.get_width() == suf2.get_width() and suf1.get_height() == suf2.get_height()):
			return False
			
		rgbaarray1 = surfarray.pixels3d(surface1)
		rgbaarray2 = surfarray.pixels3d(surface2)
		
		if rgbaarray1.shape != rgbaarray2.shape:
			return False
			
		for x in range(suf1.get_width()):
			for y in range(suf1.get_height()):
				c = rgbaarray1[x,y] - rgbaarray2[x,y]
				if (c > 0).any() or (c < 0).any():
					return False
					
		return True

	
	#灰階
	@staticmethod
	def grayscale(surface):
		monosurface = PygameGraphOperator.create((surface.get_width(), surface.get_height()), "RGBA")
		rgbaarray = surfarray.pixels3d(surface)
		monoaarray = surfarray.pixels3d(monosurface)
		monoalphaarray = surfarray.pixels_alpha(monosurface)
		
		monoaarray[:,:,0] = rgbaarray[:,:,0] // 3 + rgbaarray[:,:,1] // 3 + rgbaarray[:,:,2] // 3
		monoaarray[:,:,1] = monoaarray[:,:,0]
		monoaarray[:,:,2] = monoaarray[:,:,0]
		monoalphaarray[:,:] = 255

		return monosurface
	
	
	#超過最大值255會自動歸0
	@staticmethod
	def channelenhance(surface, rgbCuple):
		r, g, b = rgbCuple
		resultSurface = PygameGraphOperator.copy(surface)
		rbgarray = surfarray.pixels3d(resultSurface)

		rbgarray[:,:,0] = rbgarray[:,:,0] * r
		rbgarray[:,:,1] = rbgarray[:,:,1] * g
		rbgarray[:,:,2] = rbgarray[:,:,2] * b

		return resultSurface
		
	#色板分離
	"""
	@staticmethod
	def channel_split(surface, Channel):
		mono_surface = PygameGraphOperator.create((surface.get_width(), surface.get_height()), "L")
		rgbaarray = surfarray.pixels3d(surface)
		mono_rgbaarray = surfarray.pixels3d(mono_surface)
		mono_rgbaarray[:,:,0] = rgbaarray[:,:,CHANNEL_NAME[Channel]]
	"""
	
	#---貼圖系列---
	#numpy支援
	@staticmethod
	def channelpaste(dstSurface, srcSurface, dstChannel, srcChannel):
		if dstChannel != "A"	and srcChannel != "A":
			dst_rgb_array = surfarray.pixels3d(dstSurface)
			src_rgb_array = surfarray.pixels3d(srcSurface)
			dst_rgb_array[:,:, CHANNEL_NAME[dstChannel] ] = src_rgb_array[:,:, CHANNEL_NAME[srcChannel]]
		elif dstChannel == "A"	and srcChannel != "A":
			dst_alpha_array = surfarray.pixels_alpha(dstSurface)
			src_rgb_array = surfarray.pixels3d(srcSurface)
			dst_alpha_array[:,:] = src_rgb_array[:,:, CHANNEL_NAME[srcChannel]]
			#非常重要 此處有更新
			del dst_alpha_array
		elif dstChannel != "A"	and srcChannel == "A":
			dst_rgb_array = surfarray.pixels3d(dstSurface)
			src_alpha_array = surfarray.pixels_alpha(srcSurface)
			dst_rgb_array[:,:, CHANNEL_NAME[dstChannel]] = src_alpha_array[:,:]
			#非常重要 此處有更新
			del src_alpha_array
		elif dstChannel == "A"	and srcChannel == "A":
			dst_alpha_array = surfarray.pixels_alpha(dstSurface)
			src_alpha_array = surfarray.pixels_alpha(srcSurface)
			dst_rgb_array[:,:] = src_alpha_array[:,:]
			#非常重要
			del dst_alpha_array
			del src_alpha_array
	
	@staticmethod
	def setalphavalue(surface, alpha):
		dst_alpha_array = surfarray.pixels_alpha(surface)
		dst_alpha_array[:,:] = alpha
		#非常重要
		del dst_alpha_array
		
	@staticmethod
	def mulalphavalue(surface, alpha):
		dst_alpha_array = surfarray.pixels_alpha(surface)
		alpha2 = (alpha / 255.0)
		dst_alpha_array[:,:] = dst_alpha_array[:,:] * alpha2
		#非常重要
		del dst_alpha_array
		
		
	@staticmethod
	def blend(dstSurface, srcSurface, pos, blendMode=BLEND_COPY, alpha=None):
		if alpha == None:
			dstSurface.blit(srcSurface, (pos[0], pos[1]), None, blendMode)
		else:
			tempSurface = srcSurface.convert_alpha()
			PygameGraphOperator.mulalphavalue(tempSurface, alpha)
			dstSurface.blit(tempSurface, (pos[0], pos[1]), None, blendMode)
		return
	
	@staticmethod
	def laplacian(surface):
		return pygame.transform.laplacian(surface)
	
	
	@staticmethod
	def invert(surface):
		resultsurface = PygameGraphOperator.copy(surface)
		surfacearray = surfarray.pixels3d(resultsurface)
		#numpy.negative(surfacearray[:,:,:3] , surfacearray[:,:,:3])
		surfacearray[:,:,0] = 255 - surfacearray[:,:,0]
		surfacearray[:,:,1] = 255 - surfacearray[:,:,1]
		surfacearray[:,:,2] = 255 - surfacearray[:,:,2]
		return  resultsurface
		
	'''
	@staticmethod
	def blur(surface):
		image = PygameGraphOperator._convertPygame2PIL_(surface)
		image = image.filter(ImageFilter.BLUR)
		return  PygameGraphOperator._convertPIL2Pygame_(image)
	
	@staticmethod
	def smooth(surface):
		image = PygameGraphOperator._convertPygame2PIL_(surface)
		image = image.filter(ImageFilter.SMOOTH)
		return  PygameGraphOperator._convertPIL2Pygame_(image)
	'''
	
	#簡易變形系列
	"""
	@staticmethod
	def scroll( surface, offsetX, offsetY):
		resultSurface = PygameGraphOperator.copy(surface)
		resultSurface.scroll(offsetX, offsetY)
		
		return resultSurface
	
		
	@staticmethod
	def point_scroll( surface, offsetX, offsetY, point):
		x = point.x + offsetX
		if x > surface.get_width():
			x = x - surface.get_width()
			
		y = point.y + offsetY
		if y > surface.get_height():
			y = y - surface.get_height()
		return (x,y)
	"""
	
	@staticmethod
	def clip(surface, rect):
		resultSurface = surface.subsurface((rect.x, rect.y, rect.w, rect.h))
		return resultSurface.copy()
		
	@staticmethod
	def flip(surface, flipx, flipy):
		return pygame.transform.flip(surface, flipx, flipy)


	#兩軸比例縮放
	@staticmethod
	def scale_rate(surface, scale_ratex, scale_ratey):
		w = scale_ratex * surface.get_width()
		h = scale_ratey * surface.get_height()
		_scale = (int(w), int(h))
		return pygame.transform.smoothscale(surface, _scale)

	def scale_fixed(surface, scale_fixedx, scale_fixedy):
		_scale = (int(scale_fixedx), int(scale_fixedy))
		return pygame.transform.smoothscale(surface, _scale)

	@staticmethod
	def rotate(surface, angle):
		return pygame.transform.rotate(surface, angle)
	
	#垂直旋轉
	def transpose(surface, pose):
		if pose == TRANSPOSE_FORWARD:
			return pygame.transform.rotate(surface, 90)
		elif pose == TRANSPOSE_BACKWARD:
			return pygame.transform.rotate(surface, 270)
		elif pose == TRANSPOSE_OPPOSITE:
			return pygame.transform.rotate(surface, 180)
		else:
			raise TypeError("Most be TRANSPOSE_*")
			
	@staticmethod
	def colorshape(surface, color):
		alphasurface = GraphOperator.create(surface.get_size(), "RGBA")
		alphasurface.fill(color)
		GraphOperator.channelpaste(alphasurface, surface,"A", "R")
		return alphasurface
	

import ctypes
lilithapi = ctypes.CDLL("capi\\lilithapi.dll")

'''
def TestOprImage(name, surface, mothed, *pm):
		if len(pm) == 0:
			def funcObj():
				return mothed(surface)
		elif len(pm) == 1:
			def funcObj():
				return mothed(surface, pm[0])
		elif len(pm) == 2:
			def funcObj():
				return mothed(surface, pm[0], pm[1])
		
		lilithapi.timer_start()
		savesurface = funcObj()
		lilithapi.timer_print()
		print("[OPR]  %s" %(name))

		
		#print(name + " need : \t\t" + str(performance.get_interval() ))
		#print(name + " avg : \t\t" + str(performanceLoop.get_avg() ))
		pygame.image.save(savesurface, name + ".bmp")
		

'''

def createimagefuncter1(funcdict, imagesize, surface):
	Oprt = PygameGraphOperator
	funcdict["copy"] = functools.partial(Oprt.copy, surface)

	funcdict["clip"] = functools.partial(Oprt.clip, surface, Rect(1,1, imagesize-1, imagesize-1))
	funcdict["convert"] = functools.partial(Oprt.convert, surface, "RGB")
	funcdict["grayscale"] = functools.partial(Oprt.grayscale, surface)
	funcdict["laplacian"] = functools.partial(Oprt.laplacian, surface)
	funcdict["invert"] = functools.partial(Oprt.invert, surface)
	funcdict["flip"] = functools.partial(Oprt.flip, surface, False, True)
	funcdict["scale_rate"] = functools.partial(Oprt.scale_rate, surface, 1.01, 1.01)
	funcdict["scale_fixed"] = functools.partial(Oprt.scale_fixed, surface, imagesize+1, imagesize+1)
	funcdict["rotate"] = functools.partial(Oprt.rotate, surface, 7.65)
	funcdict["channelenhance"] = functools.partial(Oprt.channelenhance, surface, (0.4,1,0.85))
	funcdict["colorshape"] = functools.partial(Oprt.channelenhance, surface, (255,0,128))
	funcdict["mulalphavalue"] = functools.partial(Oprt.mulalphavalue, surface, 128)
	funcdict["setalphavalue"] = functools.partial(Oprt.setalphavalue, surface, 128)
	
	'''
	font = Font()
	textsurface = font.CreateTextSurface("haha lala猜猜我是誰?")
	TestOprImage("font_oneline", textsurface,  PygameGraphOperator.copy)
	
	textsurface = font.CreateMultilineSurface("haha lala猜猜我是誰?", 20)
	TestOprImage("font_multiline", textsurface,  PygameGraphOperator.copy)
	'''
#surfacedst要比surfacesrc在尺寸上大兩倍
#surfacedst2需要與surfacesrc同尺寸
def createimagefuncter2(funcdict, imagesize, surfacesrc, surfacedst, surfacedst2):
	Oprt = PygameGraphOperator

	pos = (imagesize // 2, imagesize // 2)
	
	dstlist = {}
	dstlist["blend"] = Oprt.copy(surfacedst)
	funcdict["blend"] = functools.partial(Oprt.blend, dstlist["blend"], surfacesrc, pos)
	dstlist["blendadd"] = Oprt.copy(surfacedst)
	funcdict["blendadd"] = functools.partial(Oprt.blend, dstlist["blendadd"], surfacesrc, pos, BLEND_ADD)
	dstlist["blendsub"] = Oprt.copy(surfacedst)
	funcdict["blendsub"] = functools.partial(Oprt.blend, dstlist["blendsub"], surfacesrc, pos, BLEND_SUB)
	dstlist["blendmul"] = Oprt.copy(surfacedst)
	funcdict["blendmul"] = functools.partial(Oprt.blend, dstlist["blendmul"], surfacesrc, pos, BLEND_MUL)
	dstlist["blendmin"] = Oprt.copy(surfacedst)
	funcdict["blendmin"] = functools.partial(Oprt.blend, dstlist["blendmin"], surfacesrc, pos, BLEND_MIN)
	dstlist["blendmax"] = Oprt.copy(surfacedst)
	funcdict["blendmax"] = functools.partial(Oprt.blend, dstlist["blendmax"], surfacesrc, pos, BLEND_MAX)
	
	#channel_paste必須同尺寸
	dstlist["channelpaste"] = Oprt.copy(surfacedst2)
	funcdict["channelpaste"] = functools.partial(Oprt.channelpaste, dstlist["channelpaste"], surfacesrc, CHANNEL_R, CHANNEL_R)
	
	return dstlist
	
def TestImageByTimes(surfacesrc, surfacedst, surfacedst2, imagesize, timeslist):
	
	if len(timeslist) >= 6:
		timeslist = timeslist[:7]
	else:
		for i in range(6 - len(timeslist)):
			timeslist.append(0)
	
	print("%16s %8d %8d %8d %8d %8d %8d" %("TestFunc", timeslist[0], timeslist[1], timeslist[2],
	                                                     timeslist[3], timeslist[4], timeslist[5]))
		
	surfacesrc = PygameGraphOperator.scale_fixed(surfacesrc, imagesize, imagesize)
	surfacedst = PygameGraphOperator.scale_fixed(surfacedst, imagesize*2, imagesize*2)
	surfacedst2 = PygameGraphOperator.scale_fixed(surfacedst2, imagesize, imagesize)
	funcdict = {}
	createimagefuncter1(funcdict, imagesize, surfacesrc)
	createimagefuncter2(funcdict, imagesize, surfacesrc, surfacedst, surfacedst2)
	
	for funckey in funcdict.keys():
		hottimelist = []
		for times in timeslist:
			lilithapi.timer_start()
			for i in range(times):
				funcdict[funckey]()
			hottime = lilithapi.timer_end()
			if times > 0:
				avg_hottime = hottime // times
			else:
				avg_hottime = hottime // 1
				
			hottimelist.append(avg_hottime)
		print("%16s %8d %8d %8d %8d %8d %8d" %(funckey, hottimelist[0], hottimelist[1], hottimelist[2],
														 hottimelist[3], hottimelist[4], hottimelist[5]))
														 
														 
def TestImageBySize(surfacesrc, surfacedst, surfacedst2, imagesizelist, times):
	
	if len(imagesizelist) >= 6:
		imagesizelist = imagesizelist[:7]
	else:
		for i in range(6 - len(imagesizelist)):
			imagesizelist.append(0)
	
	print("%16s %8d %8d %8d %8d %8d %8d" %("TestFunc", imagesizelist[0], imagesizelist[1], imagesizelist[2],
	                                                     imagesizelist[3], imagesizelist[4], imagesizelist[5]))

	sized_funcdict = {}
	for imagesize in imagesizelist:
		if imagesize == 0:
			continue
		_surfacesrc = PygameGraphOperator.scale_fixed(surfacesrc, imagesize, imagesize)
		_surfacedst = PygameGraphOperator.scale_fixed(surfacedst, imagesize*2, imagesize*2)
		_surfacedst2 = PygameGraphOperator.scale_fixed(surfacedst2, imagesize, imagesize)
		sized_funcdict[imagesize] = {}
		createimagefuncter1(sized_funcdict[imagesize], imagesize, _surfacesrc)
		createimagefuncter2(sized_funcdict[imagesize], imagesize, _surfacesrc, _surfacedst, _surfacedst2)
	
	for funckey in sized_funcdict[imagesizelist[0]].keys():
		hottimelist = []
		for imagesize in imagesizelist:
			if imagesize == 0:
				hottimelist.append(0)
				continue
				
			lilithapi.timer_start()
			for i in range(times):
				sized_funcdict[imagesize][funckey]()
			hottime = lilithapi.timer_end()
			if times > 0:
				avg_hottime = hottime // times
			else:
				avg_hottime = hottime // 1
				
			hottimelist.append(avg_hottime)
		print("%16s %8d %8d %8d %8d %8d %8d" %(funckey, hottimelist[0], hottimelist[1], hottimelist[2],
														 hottimelist[3], hottimelist[4], hottimelist[5]))
		
		
def WriteImage(surfacesrc, surfacedst, surfacedst2, imagesize):
	funcdict = {}
	createimagefuncter1(funcdict, imagesize, surfacesrc)
	for funckey in funcdict.keys():
		if funckey == "mulalphavalue" or funckey == "setalphavalue":
			continue
			
		print("now saving... " + funckey)
		savesurface = funcdict[funckey]()
		pygame.image.save(savesurface, os.path.join("testimg", funckey + ".bmp"))
		
	funcdict = {}
	dstlist = createimagefuncter2(funcdict, imagesize, surfacesrc, surfacedst, surfacedst2)
	for funckey in funcdict.keys():
		print("now saving... " + funckey)
		funcdict[funckey]()
		pygame.image.save(dstlist[funckey], os.path.join("testimg", funckey + ".bmp"))
		
def TestPygameDep(album):
	soundsys = PygameSoundSys()
	sound = album.fetch("testerimg\\close_door_2")
			   
	graphsys = PygameGraphSys()
	graphsys.open()
	#graphsys.close()
	#graphsys.reopen()
	#chn = pygame.mixer.Channel(1)
	#chn.queue(sound)
	#sound.play()
	for i in range(600):
		Tick(60)
		soundsys.playback(i)
		graphsys.flip()
		if i < 240 and i % 60 == 0:
			soundsys.addsound(sound, 7)
			
		if i == 240:
			graphsys.close()
		if i == 360:
			graphsys.reopen()
			
if __name__ == '__main__':
	pygame.display.init()
	album = PygameAlbum()
	
	TestImageByTimes(album.fetch("testerimg\\test128x128_32_1"),
					 album.fetch("testerimg\\test256x256_24"),
					 album.fetch("testerimg\\test128x128_32_2"),
					 3, [1,2,5,10,20,1000])
	print()
	
	TestImageBySize(album.fetch("testerimg\\test128x128_32_1"),
					album.fetch("testerimg\\test256x256_24"),
					album.fetch("testerimg\\test128x128_32_2"),
					[3,10,50,100,250], 20)
			  
	WriteImage(album.fetch("testerimg\\test128x128_32_1"),
			   album.fetch("testerimg\\test256x256_24"),
			   album.fetch("testerimg\\test128x128_32_2"),
			   128)
			   
	TestPygameDep(album)
	